import crc32 from 'crc-32'
import config from './config'
import experiments from './experiments'
import { getQuery } from '@/utils/base'

export default (uuid:string):string => {
  const crc32Uid = crc32.str(uuid)
  const crc32UidAbs = Math.abs(crc32Uid)
  const mod = crc32UidAbs % 10000
  const experimentArr = {}
  config.forEach(item => {
    if (item.experiment !== null) {
      const experimentSplit = (item.experiment as string)?.split('.')
      const experimentName = experimentSplit[0]
      let experimentGroup = experimentSplit[1]
      const eit = experiments[experimentName] //
      let isInTraffic = item.traffic.from <= mod && mod <= item.traffic.to
      const queryEG: string = eit && getQuery(`abtest-${eit.id}`)
      if (queryEG) {
        experimentGroup = queryEG
        isInTraffic = true
      }
      if (eit && isInTraffic) {
        const eitTime = eit.time
        const startTime = Date.parse(`${eitTime.start} GMT+8`)
        const endTime = Date.parse(`${eitTime.end} GMT+8`)
        const nowTime = Date.now()
        if (startTime < nowTime && endTime > nowTime && eit.groups.includes(experimentGroup)) {
          experimentArr[eit.id] = `${eit.id}.${experimentGroup}`
        }
      }
    }
  })
  return Object.values(experimentArr).join()
}
